//
//  NewContactViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-22.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "NewContactViewController.h"
#import "GroupAddViewController.h"
#import "StringUtil.h"
#import "User.h"
#import "UserService.h"
#import "FriendGroup.h"
#import "DBConnection.h"
#import "GuaziAppDelegate.h"
#import "REString.h"


@implementation NewContactViewController


@synthesize nameField;
@synthesize phoneField;
@synthesize contactName;
@synthesize phone;
@synthesize groupsTableView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [nameField release];
    [phoneField release];
    [groupsTableView release];
    [groups release];
    [selectGroups release];
    [contactName release];
    [phone release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

- (void) buildBarButtonItems
{
    UIBarButtonItem* leftItem = [[UIBarButtonItem alloc] initWithTitle:@"通讯录" style:UIBarButtonItemStylePlain target:self action:@selector(gotoFriendsView)];
    self.navigationItem.leftBarButtonItem = leftItem;
    [leftItem release];
    
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
                                                                               target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [rightItem release];
    
    self.navigationItem.title = @"新建联系人";
}


- (void)viewDidLoad
{
    [super viewDidLoad];
 
    [self buildBarButtonItems];
    
    selectGroups = [[NSMutableDictionary alloc] init];
    
    if ( self.phone ) {
        self.phoneField.text = phone;
    }
    
    if ( self.contactName ) {
        self.nameField.text = contactName;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.nameField = nil;
    self.phoneField = nil;
    self.groupsTableView = nil;
    self.contactName = nil;
    self.phone = nil;
    [groups release];
    [selectGroups release];
}


- (void) viewWillAppear:(BOOL)animated
{
    groups = (NSMutableArray*) [FriendGroup loadGroups:NO onlyRealGroup:YES];
    [groups retain];
    [self.groupsTableView reloadData];
    
    [super viewWillAppear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - 具体操作的方法

- (void) gotoFriendsView
{
    FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
    [controller refreshTableView];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) save
{
    self.contactName = [self.nameField.text trim];
    self.phone = [self.phoneField.text trim];
    
    NSString* message = nil;
    if ( [contactName length] == 0 ) {
        message = @"请输入联系人姓名";
    }
    else if ( [phone length] == 0 ) {
        message = @"请输入联系人手机";
    }
    else if ( ![phone checkPhone] ) {
        message = @"请输入合法的手机号";
    }
    
    if ( message ) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                        message:message 
                                                       delegate:nil 
                                              cancelButtonTitle:@"确定" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    
    User* user = [User userwithPhone:phone];
    if ( !user ) {
        user = [[[User alloc] init] autorelease];
        user.userId = [DBConnection createRandomNum:kPKBitNumberPerson];
    }
    
    user.name = phone;
    user.screenName = contactName;
    user.remark = contactName;
    user.phone = phone;
    user.relation = kUserRelationFollowing;
    user.state = kUserStateLocal;
    
    NSMutableArray* groupIds = [NSMutableArray array];
    if ( [selectGroups count] > 0 ) {
        for ( FriendGroup* group in [selectGroups allValues] ) {
            [groupIds addObject:[NSString stringWithFormat:@"%lld", group.groupId]];
        }
    }
    else {
        [groupIds addObject:@"0"];
    }
    
    [UserService addUser:user groups:groupIds];
    
    FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
    [controller refreshCreateFriendship:user];
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) selectNoneGroup:(UITableView*)tableView
{
    [selectGroups removeAllObjects];
    
    FriendGroup* group = [groups objectAtIndex:[groups count] - 1];
    [selectGroups setObject:group forKey:@"0"];
    
    for ( int i=0; i<[groups count]; i++ ) {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        if ( cell ) {
            if ( i == [groups count] - 1 ) {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }
            else {
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
    }
}


- (void) deselectNoneGroup:(UITableView*)tableView
{
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[groups count]-1 inSection:0]];
    if ( cell ) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}


- (IBAction) hiddenKeyboard
{
    [self.nameField resignFirstResponder];
    [self.phoneField resignFirstResponder];
    [self.view becomeFirstResponder];
}


- (IBAction) createGroup
{
    GroupAddViewController* controller = [[GroupAddViewController alloc] init];
    controller.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:controller action:@selector(dismiss)] autorelease];
    controller.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:controller action:@selector(saveInModelView)] autorelease];
    
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:controller];
    [self.navigationController presentModalViewController:nav animated:YES];
    [controller release];
    [nav release];
}

#pragma mark - tableview Delegate

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [groups count];
}


- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* s = @"NewContactCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:s];
    if ( cell == nil ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:s] autorelease];
    }
    
    FriendGroup* group = [groups objectAtIndex:indexPath.row];
    cell.textLabel.text = group.name;
    
    FriendGroup* g = [selectGroups objectForKey:[NSString stringWithFormat:@"%lld", group.groupId]];
    if ( g ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}


- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self hiddenKeyboard];
    
    FriendGroup* group = [groups objectAtIndex:indexPath.row];
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    if ( cell.accessoryType == UITableViewCellAccessoryCheckmark ) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [selectGroups removeObjectForKey:[NSString stringWithFormat:@"%lld", group.groupId]];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [selectGroups setObject:group forKey:[NSString stringWithFormat:@"%lld", group.groupId]];
    }
    
    return indexPath;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
